package com.itheima.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        // 注册,登录相关的资源需要无条件放行,否则无法登录
        // 保存要无条件放行的资源
        String[] uris = {"checkCodeServlet", "loginServlet", "registerServlet", "css", "imgs", "login.jsp", "register.jsp"};
        String requestURI = request.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        for (String uri : uris) {
            if (requestURI.contains(uri)) {
                // 请求的资源就是要放行的资源
                chain.doFilter(req, resp);
                return;
            }
        }

        // 判断用户是否登录
        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");

        if (username != null) {
            // 如果登录,放行
            chain.doFilter(req, resp);
        } else {
            // 如果没有登录,跳转到登录页面
            request.setAttribute("loginMessage", "请先登录!");
            request.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
